<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box {
            background-color: blue;
            width: 200px;
            height: 200px;
        }
    </style>
</head>

<body>
    <input type="text">
    <div class="box"></div>
    <script>
        //防抖 将多次操作变成一次
        let telInput = document.querySelector('input')
        telInput.addEventListener('input', antiShake(demo, 2000))
        function antiShake(fn, wait) {
            let timeOut = null;
            return args => {
                if (timeOut) clearTimeout(timeOut)
                timeOut = setTimeout(fn, wait);
            }
        }
        function demo() {
            console.log("发起请求");
        }
        //节流=》一定时间内只调用一次函数
        //应用场景 1.提交表单 2. 高频监听函数
        let box = document.querySelector(".box");
        box.addEventListener("click", throttle(demo, 2000));
        function throttle(event, time) {
            // console.log(2);
            let timer = null;
            // console.log(timer);
            return function () {
                // console.log(4);
                if (!timer) {
                    // console.log(3);
                    timer = setTimeout(() => {
                        // console.log(1);
                        event();
                        timer = null;
                    }, time);
                }
            }

        }
    </script>
</body>

</html>